import 'package:get/get.dart';
import 'package:jiffy/jiffy.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/home/device/get_device_records_list_entity.dart';
import 'package:safetymonitor/app/data/entities/home/query_params_entity.dart';
import 'package:safetymonitor/app/data/entities/home/risk_tree_entity.dart';

///设备报备
class MaintenanceController extends GetxController {
  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  /// 选中的节点
  RiskTreeEntity selectedEntity = RiskTreeEntity();
  /// 真正确定了的数据 回显用
  RiskTreeEntity selectedEntity2 = RiskTreeEntity();
  String endDate = '';
  String startDate = '';

  String endRecordDate = '结束时间';
  String startRecordDate = '开始时间';
  /// 情况说明
  String maintenanceRecords = '';

  /// 默认开始时间  null传入也是开始时间
  DateTime? startTime = DateTime.now();

  /// 报备记录列表
  List<GetDeviceRecordsListEntity> getDeviceRecordsListEntityList = [];

  /// 实际筛选确定保存的数据
  QueryParamsEntity? queryParams = QueryParamsEntity();

  selectTime() async {
    startTime = await showDatePicker(
      context: Get.context!,
      initialDate: startTime,
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      helpText: '请选择值班开始时间',
    );
    if (startTime != null) {
      startDate =
          Jiffy.parseFromDateTime(startTime!).format(pattern: 'yyyy-MM-dd');
      update();
      _selectEndTime();
    }
  }

  ///结束时间选取
  _selectEndTime() async {
    final DateTime? endTime = await showDatePicker(
        context: Get.context!,
        initialDate: startTime,
        firstDate: DateTime(2000),
        lastDate: DateTime(2100),
        helpText: '请选择值班结束时间');
    if (endTime != null) {
      endDate = Jiffy.parseFromDateTime(endTime).format(pattern: 'yyyy-MM-dd');
      update();
    }
  }

  /// 重置
  void reset() {
    riskRightScaffoldKey.currentState?.closeEndDrawer();
    selectedEntity = RiskTreeEntity();
    selectedEntity2 = RiskTreeEntity();
    queryParams = QueryParamsEntity();
    //置空
    startDate = '';
    endDate = '';
    maintenanceRecords = '';
    getDeviceRecordsListEntityList.clear();
    update();
  }

  /// 确定
  void confirm() {
    if (selectedEntity.nodeType != 4) {
      AppToast.show('请选具体设备~');
      return;
    }
    //置空
    startDate = '';
    endDate = '';
    maintenanceRecords = '';
    queryParams = selectedEntity.queryParams;
    queryParams?.nodeName=selectedEntity.nodeName??'';
    //获取当前设备的记录
    deviceRecordsGetList();
    riskRightScaffoldKey.currentState?.closeEndDrawer();

    selectedEntity2= selectedEntity;
    update();
  }

  /// 筛选按钮
  void onFilterButtonPressed() {
      //判断选中的节点和确定选中的节点是否一致 不一致 就设置成一致的
    if(selectedEntity!=selectedEntity2){
      selectedEntity=selectedEntity2;
    }
    riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  /// 提交
  void submit() async {
    //判断
    if (queryParams?.deviceCode == null || queryParams!.deviceCode!.isEmpty) {
      AppToast.show('请选择维修设备');
      return;
    }
    if (startDate.isEmpty) {
      AppToast.show('请选择报备维修开始时间');
      return;
    }
    if (endDate.isEmpty) {
      AppToast.show('请选择报备维修结束时间');
      return;
    }
    final res = await HttpUtil().generatePostRequest(
      Interface.deviceRecordsCreate,
      data: {
        //{companyId: 121, systemId: 19, systemCode: nbwy, deviceCode: 61050300010430}
        'companyId': queryParams?.companyId,
        'systemId': queryParams?.systemId,
        'deviceCode': queryParams?.deviceCode,
        'monitorCode': queryParams?.systemCode,
        'operators': UserManager.getUser()?.nickname,
        'operatorsId': UserManager.getUser()?.id,
        'maintenanceRecords': maintenanceRecords,
        'operationTimeStart': startDate,
        'operationTimeEnd': endDate
      },
    ).execute(isShowLoading: true);
    res.onSuccess((result) {
      // 移除焦点
      FocusManager.instance.primaryFocus?.unfocus();
      AppToast.showSuccess('保存成功~');
      //  2.报备记录接口
      deviceRecordsGetList();
    });
  }

  /// 获得新设备维护记录列表
  void deviceRecordsGetList() async {
    final res = await HttpUtil()
        .generateGetRequest<List<GetDeviceRecordsListEntity>>(
            Interface.deviceRecordsGetList,
            queryParameters: {
          'companyId': queryParams?.companyId,
          'systemId': queryParams?.systemId,
          'deviceCode': queryParams?.deviceCode,
          'monitorCode': queryParams?.systemCode,
          'operationTimeStart': startRecordDate=='开始时间'?null:startRecordDate,//设备维护开始时间
          'operationTimeEnd': endRecordDate=='结束时间'?null:endRecordDate,
        }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getDeviceRecordsListEntityList = result.data!;
        update();
      }
    });
  }

  /// 删除 id
  void del(int? id) async {
    final res = await HttpUtil().generateDeleteRequest(
      Interface.deviceRecordsDelete,
      queryParameters: {'id': id},
    ).execute();
    res.onSuccess((result) {
      AppToast.showSuccess('删除成功');
      deviceRecordsGetList();
    });
  }

  @override
  void onInit() {
    super.onInit();
    // 是否获取最新的一条  暂时不要
    // _deviceRecordsGetFirst();
  }

  /// 获得新设备维护记录列表
  void _deviceRecordsGetFirst() async {
    final res = await HttpUtil().generateGetRequest<GetDeviceRecordsListEntity>(
        Interface.deviceRecordsGetFirst,
        queryParameters: {
          'companyId': queryParams?.companyId,
          'systemId': queryParams?.systemId,
          'deviceCode': queryParams?.deviceCode,
          'monitorCode': queryParams?.systemCode,
        }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getDeviceRecordsListEntityList.add(result.data!);
        //给页面赋值  ---
        queryParams?.companyId = result.data!.companyId;
        queryParams?.systemId = result.data!.systemId;
        queryParams?.deviceCode = result.data!.deviceCode;
        queryParams?.systemCode = result.data!.monitorCode;
        maintenanceRecords = result.data!.maintenanceRecords ?? '';
        startDate = result.data!.operationTimeStart ?? '';
        endDate = result.data!.operationTimeStart ?? '';
        update();
      }
    });
  }
}
